package com.etlmaster.executor.steps.file;

import com.etlmaster.executor.Step;
import com.etlmaster.executor.StepMeta;
import com.etlmaster.executor.annotation.StepInstruction;
import com.etlmaster.executor.processors.File.FileScanInfo;
import com.etlmaster.executor.processors.File.FileScaner;
import com.etlmaster.executor.utils.DpVfsUtils;
import com.etlmaster.executor.utils.StepState;

import java.util.List;

/**
 * 
 * @author MeiKefu
 * @date 2015-1-8
 * @date 2015-2-16
 */
@StepInstruction("fileScan")
public class FileScanStep extends Step {

	private FileScanStepMeta meta;

	public FileScanStep(StepMeta meta) {
		super(meta);
		this.meta = ((FileScanStepMeta) meta);
	}

	public int handle() {
		List<FileScanInfo> foundFiles = null;
		FileScaner fileScaner = new FileScaner();
		fileScaner.setIntervalDay(meta.getIntervalday());
		fileScaner.setRegex(meta.getFileNameFilter());
		fileScaner.setIsDepthwise(meta.isDepthwise());
		fileScaner.setBefore(Boolean.parseBoolean(meta.getBefore()));
		for (String vfsDir : meta.getSourceDirs()) {
			vfsDir = meta.variableSubstitution(vfsDir, DpVfsUtils.getInstance()
					.buildEscapeData());
			fileScaner.setPath(vfsDir);
			fileScaner.scanAndCheckResult();
		}
		foundFiles=fileScaner.foundFiles;
		if ((foundFiles != null) && (foundFiles.size() > 0)) {

			meta.log("INFO", "匹配正则{}，共找到{}个文件",
					meta.getFileNameFilter(), foundFiles.size() + "");
		} else {
			meta.log("WARN", "匹配正则{}，未发现文件", meta.getFileNameFilter());

		}
		meta.getStepState().getReturnValue().put("foundFiles", foundFiles);
		return StepState.RUNNING_SUCCESSED;
	}

	public boolean stop() {
		return false;
	}

}